package com.zkj.interceptor;

import com.zkj.constant.JwtClaimsConstant;
import com.zkj.constant.MessageConstant;
import com.zkj.context.BaseContext;
import com.zkj.exception.EmployeeNotLoginException;
import com.zkj.properties.JwtProperties;
import com.zkj.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: zhangKaiJun
 * @createTime：2024/8/26
 * @description：
 */
@Slf4j
@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("JwtTokenAdminInterceptor拦截器执行了");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());
        // 处理token，如果token有效，就执行，没效就让前端退出未登录
        try {
            log.info("token:{}", token);
            // token:eyJhbGciOiJIUzI1NiJ9.eyJlbXBJZCI6MiwiZXhwIjoxNzI0NzMwMDU3fQ.OdJyshVj59_ogavs5bfFx-aqpkhMr4L8Sy0DbP8dCkU
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            log.info("claims:{}", claims);
            // claims:{empId=2, exp=1724730057}
            Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("当前empId:{}", empId);
            // 当前empId:2
            BaseContext.setCurrentId(empId);
            return true;
        } catch (Exception e) {
            throw new EmployeeNotLoginException(MessageConstant.TOKEN_INVALID, 401);
        }
    }
}
